package com.share.shareplatform.shareuser.util;

import com.share.shareplatform.pojo.Authority;
import com.share.shareplatform.shareuser.dao.AuthorityDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;

@Component
public class AuthorityOperation {
    @Autowired
    private AuthorityDao authorityDao;


    private static final HashMap<String, String> OPERATION_CONSTANTS = new HashMap<>();

    private String resolveOperation(Integer operation, String module) {
        int[] array = {16, 8, 4, 2, 1};
        String[] result = {"Super", "Delete", "Update", "Add", "Find"};
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            if (operation - array[i] >= 0) {
                operation -= array[i];
                builder.append(module + result[i] + ",");
            }
        }
        //删除最后一个','
        if (builder.charAt(builder.length() - 1) == ',') {
            builder.deleteCharAt(builder.length() - 1);
        }

        return builder.toString();
    }


    //在初始化完后执行该方法，也可以在构造器中传入需要的参数  参考https://www.cnblogs.com/virgosnail/p/10257040.html
    @PostConstruct
    public void init() {
        try {
            List<Authority> list = authorityDao.findAll();
            list.forEach(authority -> {
                String module = authority.getModule();
                Integer operation = authority.getOperation();
                String resolveOperation = resolveOperation(operation, module);
                String key = module + operation;
                OPERATION_CONSTANTS.put(key, resolveOperation);
            });
            OPERATION_CONSTANTS.values().forEach(a -> {
                System.out.println(a);
            });

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }


    }

    public static String getOperation(String key) {
        return OPERATION_CONSTANTS.get(key);
    }
}
